//
//  LCAppDelegate.m
//
//
//  Created by admin on 2017/1/6.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "LCAppDelegate.h"
#import <BaiduMobStat.h>
#import <Bugly/Bugly.h>
#import "WXApi.h"

@interface LCAppDelegate ()  <WXApiDelegate>

@end

@implementation LCAppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [self setupUserAgent];///设置浏览器 代理标识
    //初始化Bugly
    [Bugly startWithAppId:@"ca9031c1ef"];

    [[BaiduMobStat defaultStat] startWithAppId:@"736f722da8"];//百度统计
    
    //微信登录
    [WXApi registerApp:@"wx09ccd230baf5b6ec"];
 
    [self setupShareSDK];
    return YES;
}
///设置ShareSDK
- (void)setupShareSDK {
    
    [ShareSDK registerActivePlatforms:@[ @(SSDKPlatformTypeWechat) ]
     
                             onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             default:
                 break;
         }
     }
                      onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wx09ccd230baf5b6ec"
                                       appSecret:@"dd6d8ecb126b4adfde1603b15e0e760c"];
                 break;
             default:
                 break;
         }
     }];
}
// 实现和微信终端交互的具体请求与回应，因此需要实现WXApiDelegate协议的两个方法：
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [WXApi handleOpenURL:url delegate:self];
    });
    return YES;
}

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<NSString *,id> *)options
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [WXApi handleOpenURL:url delegate:self];
    });
    return YES;
}
-(void)onReq:(SendAuthReq *)req{
    NSLog(@"req = %@", req);
}
-(void)onResp:(SendAuthResp *)resp{
    [SVProgressHUD dismiss];
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        return;
    }
    NetworkTool *networkTool = [NetworkTool sharedInstance];
    if (resp.errCode == 0) {
        NSLog(@"errCode = %d", resp.errCode);
        NSLog(@"code = %@", resp.code);
        NSLog(@"state = %@", resp.state);
        NSLog(@"state = %@", resp.lang);
        NSLog(@"state = %@", resp.country);
        NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",@"wx09ccd230baf5b6ec",@"dd6d8ecb126b4adfde1603b15e0e760c",resp.code];
        
        [networkTool GETWithUrlString:url parameters:@{} success:^(id responseObject) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:NULL];

//            NSLog(@"dict = %@", dict);
            
            NSString *access_token = dict[@"access_token"];
            NSString *openid = dict[@"openid"];
            NSString *unionid = dict[@"unionid"];
//            NSString *refresh_token = dict[@"refresh_token"];
//            NSLog(@"openid = %@", openid);
//            NSLog(@"unionid = %@", unionid);
//            NSLog(@"refresh_token = %@", refresh_token);
//
            NSString *getUserInfoURL = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token,openid];

            [networkTool GETWithUrlString:getUserInfoURL parameters:@{} success:^(id responseObject) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:NULL];
                NSLog(@"dict = %@", dict);
                NSString *nickname = dict[@"nickname"];
                NSString *headimgurl = dict[@"headimgurl"];
                LCAccountManager *accountManager = [LCAccountManager sharedInstance];
                accountManager.userName = nickname;
                accountManager.userPicUrl = headimgurl;
                //存储userName
                NSLog(@"_AccM.userName = %@", _AccM.userName);
                NSLog(@"_AccM.userPicUrl = %@", _AccM.userPicUrl);

                
            } failure:^(NSError *error) {
                NSLog(@"error = %@", error);
            }];
            NSDictionary *parameters = @{@"openid":openid,
                                         @"unionid":unionid,
                                         @"type":@"1"
                                         };

            [LSZRequestTotal initWithPostRequest:@"http://toutiao.api.inping.com/user/sns_bind" :parameters :^(BOOL isOK, NSString *string, NSDictionary *dict) {
                if (isOK == YES) {
//                    NSLog(@"dict = %@", dict);
//                    NSLog(@"data = %@", dict[@"data"]);
                }
                [SVProgressHUD showSuccessWithStatus:dict[@"msg"]];
                [SVProgressHUD dismissWithDelay:1.0f];
            }];
            

        } failure:^(NSError *error) {
            NSLog(@"error = %@", error);
        }];
    }
    
    
}

///设置浏览器 代理标识
- (void)setupUserAgent {
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString *newUserAgent = [userAgent stringByAppendingString:@" CK 2.0"];//自定义需要拼接的字符串
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}

//- (void)dealwithCrashMessage:(NSNotification *)note {
////    注意:所有的信息都在userInfo中
////    你可以在这里收集相应的崩溃信息进行相应的处理(比如传到自己服务器)
//    ISLog(@"note.userInfo= %@",note.userInfo);
//}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
